package com.gsmr.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.gsmr.entity.GPRS_default;
import com.gsmr.entity.PageBean;
import com.gsmr.service.GPRS_defaultService;
import com.gsmr.util.DateUtil;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.ResponseUtil;
import com.gsmr.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author 作者 : 黄志新
 * @version 创建时间：2017年8月11日 上午12:13:57 类说明：GPRS_defaultController层
 */
@Controller
@RequestMapping("/gprs_default")
public class GPRS_defaultController {

	@Resource
	private GPRS_defaultService gprs_defaultService;

	List<GPRS_default> gprs_defaultList;

	/**
	 * 分页条件查询GPRS_default
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value = "page", required = false) String page, @RequestParam(value = "rows", required = false) String rows, 
			@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime, 
			@RequestParam(value = "IMSI", required = false) Integer IMSI,@RequestParam(value = "TLLIs", required = false) String TLLIs, 
			@RequestParam(value = "MSISDN", required = false) String MSISDN, @RequestParam(value = "CTCS_ID", required = false) String CTCS_ID, 
			@RequestParam(value = "MessageType", required = false) String MessageType, @RequestParam(value = "TLLI", required = false) String TLLI, 
		@RequestParam(value = "SourceIP", required = false) String SourceIP, @RequestParam(value = "DestinationIP", required = false) String DestinationIP, 
		@RequestParam(value = "search", required = false) String search, @RequestParam(value = "increase", required = false) String increase, 
		@RequestParam(value = "recordId", required = false) String recordId, GPRS_default gprs_default, @RequestParam(value = "gEngineNo", required = false) String gEngineNo, 
		@RequestParam(value = "gTrainNo", required = false) String gTrainNo, @RequestParam(value = "BSName", required = false) String BSName,
		HttpServletResponse response) throws Exception {
		if (search == null) return;
		// System.out.println(gEngineNo);
		// System.out.println(checihao);
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("table_name", "gprs_default");
		map.put("recordId", recordId);
		map.put("IMSI", IMSI);
		map.put("MSISDN", MSISDN);
		map.put("CTCS_ID", CTCS_ID);
		map.put("MessageTypeAll", MessageType);
		map.put("TLLI", TLLI);
		map.put("SourceIP", SourceIP);
		map.put("DestinationIP", DestinationIP);
		map.put("start", pageBean.getStart());
		map.put("recordId", recordId);
		map.put("gEngineNo", gEngineNo);
		map.put("gTrainNo", gTrainNo);
		map.put("size", pageBean.getPageSize());

		if (StringUtil.isNotEmpty(BSName)) {
			String[] subName = BSName.split(",");
			map.put("BSNames", Arrays.asList(subName));
		}

		List<String> table_names = findTableName(MessageType, TLLIs, startTime, endTime, map);

		gprs_defaultList = new ArrayList<>();
		if (table_names != null && table_names.size() > 0) {
			map.put("start", 0);
			map.put("size", pageBean.getPageSize());
			if (increase.equals("1")) {
				for (int i = table_names.size() - 1; i >= 0 && gprs_defaultList.size() < pageBean.getPageSize(); i--) {
					map.put("table_name", table_names.get(i));
					List<GPRS_default> sub_gprs_defaultList = gprs_defaultService.findASC(map);
					gprs_defaultList.addAll(sub_gprs_defaultList);
				}
			} else {
				for (int i = 0; i < table_names.size() && gprs_defaultList.size() < pageBean.getPageSize(); i++) {
					map.put("table_name", table_names.get(i));
					List<GPRS_default> sub_gprs_defaultList = gprs_defaultService.find(map);
					gprs_defaultList.addAll(sub_gprs_defaultList);
				}
			}
		}
		GPRS_defaultController.ListSort(gprs_defaultList);
		if (gprs_defaultList.size() > pageBean.getPageSize() && increase.equals("1")) {
			gprs_defaultList = gprs_defaultList.subList(0, pageBean.getPageSize());
		} else if (gprs_defaultList.size() > pageBean.getPageSize() && increase.equals("0")) {
			gprs_defaultList = gprs_defaultList.subList(gprs_defaultList.size() - pageBean.getPageSize(), gprs_defaultList.size());
		}

		/*
		 * 避免返回到第一页不够100条
		 */
		if (gprs_defaultList.size() < pageBean.getPageSize() && increase.equals("0") && gprs_defaultList.size() > 0) {
			long tmptime1 = gprs_defaultList.get(0).getUnixTimeStamp();
			map.put("endTime", null);
			map.put("startTime", DateUtil.longToString(tmptime1, "yyyyMMdd"));
			table_names = gprs_defaultService.findTableNames(map);
			map.put("endTime", tmptime1);
			gprs_defaultList.clear();
			if (table_names != null) {
				map.put("start", 0);
				map.put("size", pageBean.getPageSize());
				for (int i = table_names.size() - 1; i >= 0 && gprs_defaultList.size() < pageBean.getPageSize(); i--) {
					map.put("table_name", table_names.get(i));
					List<GPRS_default> sub_gprs_defaultList = gprs_defaultService.findASC(map);
					gprs_defaultList.addAll(sub_gprs_defaultList);
				}
			}
			GPRS_defaultController.ListSort(gprs_defaultList);
			if (gprs_defaultList.size() > pageBean.getPageSize()) {
				gprs_defaultList = gprs_defaultList.subList(0, pageBean.getPageSize());
			}
		}
		setupData(gprs_defaultList);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(gprs_defaultList);
		result.put("rows", jsonArray);
		result.put("total", Integer.MAX_VALUE);
		ResponseUtil.write(response, result);
	}

	/**
	 * 查找IMSI列表
	 */
	@RequestMapping("/gprs_defaultIMSIComboList")
	public void gprs_defaultIMSIComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("table_name", "gprs_default");
		List<GPRS_default> gprs_defaultList = gprs_defaultService.findIMSIs(map);
		JSONArray rows = JSONArray.fromObject(gprs_defaultList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
	}

	/**
	 * 查找MSISDN列表
	 */
	@RequestMapping("/gprs_defaultMSISDNComboList")
	public void gprs_defaultMSISDNComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("table_name", "gprs_default");
		List<GPRS_default> gprs_defaultList = gprs_defaultService.findMSISDNs(map);
		JSONArray rows = JSONArray.fromObject(gprs_defaultList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
	}

	/**
	 * 查找Message_TYPE列表
	 */
	@RequestMapping("/gprs_defaultMessage_TYPEComboList")
	public void gprs_defaultMessage_TYPEComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("table_name", "gprs_default");
		List<GPRS_default> gprs_defaultList = gprs_defaultService.findMessage_TYPEs(map);
		JSONArray rows = JSONArray.fromObject(gprs_defaultList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
	}

	private List<String> findTableName(String MessageType, String TLLIs, String startTime, String endTime, Map<String, Object> map) {

		if (MessageType != null && MessageType.length() > 1) {
			String[] subUmType = MessageType.split(",");
			List<String> subList = Arrays.asList(subUmType);
			map.put("MessageType", subList);
		} else {
			map.put("MessageType", "");
		}

		if (TLLIs != null && TLLIs.length() > 0) {
			String[] TLLIList = TLLIs.split(",");
			List<String> TLLIList2 = Arrays.asList(TLLIList);
			map.put("TLLIs", TLLIList2);
		} else {
			map.put("TLLIs", null);
		}

		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", DateUtil.longToString(Long.parseLong(startTime), "yyyyMMdd"));
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", DateUtil.longToString(Long.parseLong(endTime), "yyyyMMdd"));
		}

		List<String> table_names = gprs_defaultService.findTableNames(map);
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", DateUtil.longToString(Long.parseLong(startTime), "yyyy-MM-dd HH:mm:ss"));
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", DateUtil.longToString(Long.parseLong(endTime), "yyyy-MM-dd HH:mm:ss"));
		}

		return table_names;
	}

	private void setupData(List<GPRS_default> gprs_defaultList) {
		for (GPRS_default o : gprs_defaultList) {
			if (o.getTLLI() != null && o.getTLLI().length() > 0) {
				try {
					Long a = Long.valueOf(o.getTLLI());
					o.setTLLI(Long.toHexString(a).toString().toUpperCase());
				} catch (Exception e) {

				}
			}
			if (o.getDirection() != null && o.getDirection().length() > 0) {
				o.setDirection(o.getDirection().equals("UPLINK") ? "上行" : "下行");
			}
		}
	}

	private String headers[] = { "触发时间", "IMSI", "TLLI", "BCCH", "TCH", "时隙号", "USF","TFI","帧号", "小区名称", "方向", "机车号", "车次号", "Um接口消息类型", "DataLayer", "源IP地址",
			"目的IP地址", "解码信息", "数据长度", "LEVEL", "SNR", "QUALITY", "数据源码", "LAC", "CI", "前置机号", "记录号" };

	/**
	 * 导出GPRS_default
	 */
	@RequestMapping("/export")
	public void export(@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime,
					   @RequestParam(value = "IMSI", required = false) String IMSI , @RequestParam(value = "TLLIs", required = false) String TLLIs,
					   @RequestParam(value = "CTCS_ID", required = false) String CTCS_ID, @RequestParam(value = "MessageType", required = false) String MessageType,
					   @RequestParam(value = "TLLI", required = false) String TLLI, @RequestParam(value = "BSName", required = false) String BSName,
					   @RequestParam(value = "recordId", required = false) String recordId, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("table_name", "gprs_default");
		map.put("IMSI", IMSI);
		map.put("CTCS_ID", CTCS_ID);
		map.put("MessageTypeAll", MessageType);
		map.put("TLLI", TLLI);
		
		if (StringUtil.isNotEmpty(BSName)) {
			map.put("BSNames", Arrays.asList(BSName.split(",")));
		}

		List<String> table_names = findTableName(MessageType, TLLIs, startTime, endTime, map);
		
		List<GPRS_default> gprs_defaultList_all = new ArrayList<>();
		List<GPRS_default> sub_gprs_defaultList = null;
		if (table_names != null && table_names.size() > 0) {
			map.put("start", 0);
			for (int i = table_names.size() - 1; i >= 0 && gprs_defaultList_all.size() <= ExcelUtil.maxExportRows; i--) {
				map.put("size", ExcelUtil.maxExportRows - gprs_defaultList_all.size());
				sub_gprs_defaultList = null;
				map.put("table_name", table_names.get(i));
				sub_gprs_defaultList = gprs_defaultService.findASC(map);
				if (sub_gprs_defaultList != null) {
					gprs_defaultList_all.addAll(sub_gprs_defaultList);
				}
			}
		}
		GPRS_defaultController.ListSort(gprs_defaultList_all);
		List<GPRS_default> sub_gprs_defaultList_all = gprs_defaultList_all;
		if (gprs_defaultList_all.size() > ExcelUtil.maxExportRows) {
			sub_gprs_defaultList_all = gprs_defaultList_all.subList(0, ExcelUtil.maxExportRows);
		}
		setupData(sub_gprs_defaultList_all);
		Workbook wb = new HSSFWorkbook();
		ExcelUtil.fillExcelData_GPRS_default(sub_gprs_defaultList_all, wb, headers);
		ResponseUtil.export(response, wb, "MAC/RLC信令" + FormatDate.formatDate() + ".xls");
	}

	/**
	 * 导出当前页的数据
	 */
	@RequestMapping("/exportcurrentpage")
	public void exportcurrentpage(@RequestParam(value = "data") String data, HttpServletResponse response) throws Exception {

		if (data == null || data.equals("null") || data.length() < 2) return;

		JSONArray jsonArray = JSONArray.fromObject(data);

		List<GPRS_default> gprsdefaultList_all = (List<GPRS_default>) JSONArray.toCollection(jsonArray, GPRS_default.class);

		Workbook wb = new HSSFWorkbook();
		ExcelUtil.fillExcelData_GPRS_default(gprsdefaultList_all, wb, headers);
		ResponseUtil.export(response, wb, "MAC/RLC信令" + FormatDate.formatDate() + ".xls");
	}

	/**
	 * 用模板导出用户
	 */
	@RequestMapping("/exportByTemplate")
	public void exportByTemplate(@RequestParam(value = "ids") String ids, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<GPRS_default> gprs_defaultList = new ArrayList<GPRS_default>();
		if (ids != null && !ids.equals("null") && !ids.equals("")) {
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("ids", idsList);
			gprs_defaultList.clear();
			List<GPRS_default> sub_gprs_defaultList = null;
			List<String> table_names = gprs_defaultService.findTableNames(map);
			if (table_names != null) {
				for (int i = 0; i < table_names.size(); i++) {
					sub_gprs_defaultList = null;
					map.put("table_name", table_names.get(i));
					sub_gprs_defaultList = gprs_defaultService.findByIds(map);
					if (sub_gprs_defaultList != null) {
						gprs_defaultList.addAll(sub_gprs_defaultList);
					}
				}
			}

			GPRS_defaultController.ListSort(gprs_defaultList);

			Workbook wb = ExcelUtil.fillExcelDataWithTemplate_GPRS_default(gprs_defaultList, "gprs_defaultExportTemplate.xls");
			ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
		} else {
			gprs_defaultList.clear();
			List<GPRS_default> sub_gprs_defaultList = null;
			List<String> table_names = gprs_defaultService.findTableNames(map);
			if (table_names != null) {
				for (int i = 0; i < table_names.size(); i++) {
					sub_gprs_defaultList = null;
					map.put("table_name", table_names.get(i));
					sub_gprs_defaultList = gprs_defaultService.find(map);
					if (sub_gprs_defaultList != null) {
						gprs_defaultList.addAll(sub_gprs_defaultList);
					}

				}
			}
			GPRS_defaultController.ListSort(gprs_defaultList);
			Workbook wb = ExcelUtil.fillExcelDataWithTemplate_GPRS_default(gprs_defaultList, "gprs_defaultExportTemplate.xls");
			ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
		}
	}

	/**
	 * 对List中每个对象元素逆序排序
	 */
	private static void ListSort(List<GPRS_default> list) {
		if (list == null || list.size() < 2) return;
		Collections.sort(list, new Comparator<GPRS_default>() {
			@Override
			public int compare(GPRS_default sf1, GPRS_default sf2) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
				try {
					Date dt1 = format.parse(sf1.getStartTime());
					Date dt2 = format.parse(sf2.getStartTime());
					if (dt1.getTime() < dt2.getTime()) {
						return -1;
					} else if (dt1.getTime() > dt2.getTime()) {
						return 1;
					} else {
						return 0;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
	}
}